package edu.njust.httpmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.njust.httpmanager.entity.Api;
import edu.njust.httpmanager.entity.Catalog;
import edu.njust.httpmanager.entity.dto.CatalogDto;
import edu.njust.httpmanager.mapper.ApiMapper;
import edu.njust.httpmanager.mapper.CatalogMapper;
import edu.njust.httpmanager.service.ICatalogService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Goal
* @description 针对表【catalog(目录)】的数据库操作Service实现
* @createDate 2023-09-03 16:51:53
*/
@Service
public class CatalogServiceImpl extends ServiceImpl<CatalogMapper, Catalog>
    implements ICatalogService {

    @Resource
    private CatalogMapper catalogMapper;

    @Resource
    private ApiMapper apiMapper;

    @Override
    public List<CatalogDto> getAllByProgramId(Long programId) {
        // 定义查询条件
        LambdaQueryWrapper<Catalog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Catalog::getProgramId, programId);

        // 执行查询
        List<Catalog> catalogs = catalogMapper.selectList(queryWrapper);

        // 合并结果
        List<CatalogDto> catalogDtos = catalogs.stream().map((item) -> {
            CatalogDto catalogDto = new CatalogDto();

            // 拷贝原有属性
            BeanUtils.copyProperties(item, catalogDto);

            // 获取目录id
            Long catalogId = item.getId();

            // 查询Api
            LambdaQueryWrapper<Api> apiLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apiLambdaQueryWrapper.eq(Api::getCatalogId, catalogId);
            // 执行查询
            List<Api> apis = apiMapper.selectList(apiLambdaQueryWrapper);

            // 封装到dto对象
            catalogDto.setApis(apis);

            // 返回结果
            return catalogDto;
        }).collect(Collectors.toList());

        return catalogDtos;
    }

    @Override
    @Transactional  // 涉及多表增删改开启事务管理
    //删除Catalog同时删除其中所有API
    public void deleteCatalog(Long id){
        //删除Catalog
        this.removeById(id);
        //删除Catalog所有api
        LambdaQueryWrapper<Api> apiWrapper = new LambdaQueryWrapper<>();
        apiWrapper.eq(Api::getCatalogId, id);
        apiMapper.delete(apiWrapper);
    }
}





